<?php
	session_start();

/*™*******************************************************************************************™*/

	// include script
	require("./inc/config-system.inc.php");
	require("./inc/config-db.inc.php");
	require("./inc/fm.inc.php");
	require("./class/adodb/adodb.inc.php");
	require("./class/validate/validate.inc.php");

/*™*******************************************************************************************™*/

	// validate data input

    // set rule for each input field
	if (isset($_POST["BTTdeldoc"])) {

		$position = 0;
		$inputLabel[] = "เอกสารที่ต้องการลบ";
		$ruleElement["TXTdeldoc"][0] = array
			(
				"checkNotEmpty" => $inputLabel[$position]
			);

		// validate rule header
		$errorMessageJSON = validateElementAdminAccount($ruleElement, 0); // see in fm.inc.php

		if (!empty($errorMessageJSON)) {
			echo $errorMessageJSON; // return json format
			exit();
		} else {
			$inputLabel = array();
			$ruleElement = array();
			$position = 0;
		}

	} else {

		$position = 0;
		$inputLabel[] = "วันที่";
		$ruleElement["TXTdoc_date"][0] = array
			(
				"checkNotEmpty" => $inputLabel[$position]
			);

		$position = $position + 1;
		$inputLabel[] = "รายการ";
		$ruleElement["TXTdescription"][0] = array
			(
				"checkNotEmpty" => $inputLabel[$position]
			);

		// validate rule header
		$errorMessageJSON = validateElementAdminAccount($ruleElement, 0); // see in fm.inc.php

		if (!empty($errorMessageJSON)) {
			echo $errorMessageJSON; // return json format
			exit();
		} else {
			$inputLabel = array();
			$ruleElement = array();
			$position = 0;
		}

		if ( $_POST["TXTshuttlecock"][0] == "" && $_POST["TXTsoftdrink"][0] == "" && $_POST["TXTmineral"][0] == "" && $_POST["TXTwater"][0] == "") {
			echo "{";
			echo '"ERROR":"กรุณาใส่ข้อมูลตัวเลข ลูกขนไก่ หรือ น้ำอัดลม หรือ น้ำเกลือแร่ หรือ น้ำดื่ม อย่างใดอย่างหนึ่งหรือมากกว่า"';
			echo "}";
			exit();
		}

		// validate rule item
		for ($index = 0; $index <= (int) $_POST["HIDnum_row"]; $index++) {

			$position = 0;
			$inputLabel[] = "รายการ";
			$ruleElement["TXTdescription"][$index] = array
				(
					"checkNotEmpty" => $inputLabel[$position]
				);

			$position = $position + 1;
			$inputLabel[] = "ชื่อผู้ชำระเงิน";
			$ruleElement["SELpayer"][$index] = array
				(
					"checkNotSelect" => $inputLabel[$position]
				);

			// validate rule
			$errorMessageJSON = validateElementAdminAccount($ruleElement, $index); // see in fm.inc.php

			if (!empty($errorMessageJSON)) {
				echo $errorMessageJSON; // return json format
				exit();
			} else {
				$inputLabel = array();
				$ruleElement = array();
				$position = 0;
			}

			if ( $_POST["TXTshuttlecock"][$index] == "" && $_POST["TXTsoftdrink"][$index] == "" && $_POST["TXTmineral"][$index] == "" && $_POST["TXTwater"][$index] == "") {
				echo "{";
				echo '"ERROR":"กรุณาใส่ข้อมูลตัวเลข ลูกขนไก่ หรือ น้ำอัดลม หรือ น้ำเกลือแร่ หรือ น้ำดื่ม อย่างใดอย่างหนึ่งหรือมากกว่า"';
				echo "}";
				exit();
			}

		}

	}

/*™*******************************************************************************************™*/

	// connection database
	$objConn = ADONewConnection(DB_DRIVER);
	$objConn->Connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	//$objConn->debug = TRUE;

	if (isset($_POST["BTTdeldoc"])) {

		// check exist doc
		$sqlCommand = "SELECT * FROM tbl_adj WHERE adj_docno = '" . $_POST["TXTdeldoc"][0] . "' AND adj_type = 'ADJ1'";
		$recordset = $objConn->Execute($sqlCommand);

		if ($recordset->RecordCount() <= 0) {
			echo "{";
			echo '"POSTING_ERROR":"ไม่พบเอกสารเลขที่ ' . $_POST["TXTdeldoc"][0] . ' ในระบบ ไม่สามารถทำการลบเอกสารได้"';
			echo "}";
			exit();
		}

		// check date to delete doc if < system date -> ignore
		if (strtotime(date("Y-m-d", $recordset->fields["created_date"])) < strtotime(date("Y-m-d", time()))) {
			echo "{";
			echo '"POSTING_ERROR":"ไม่สามารถลบเอกสารเลขที่ ' . $_POST["TXTdeldoc"][0] . ' ได้ เนื่องจากเกินกำหนดวัน"';
			echo "}";
			exit();
		}

		// update status
		$sqlCommand = "UPDATE tbl_adj SET deleted = 1 WHERE adj_docno = '" . $_POST["TXTdeldoc"][0] . "' AND adj_type = 'ADJ1'";
		$objConn->Execute($sqlCommand);

		$location = "./adj1_form.php";
		echo "{";
		echo '"POSTING_SUCCESS":"ลบเอกสารเลขที่ ' . $_POST["TXTdeldoc"][0] . ' เรียบร้อยแล้ว",';
		echo '"POSTING_REDIRECT":"' . urlencode($location) . '"';
		echo "}";
		exit();

	}

	// add data into database
	$total_amount_shuttlecock = 0;
	$total_amount_softdrink = 0;
	$total_amount_mineral = 0;
	$total_amount_water = 0;

	// get running no.
	$sqlCommand = "SELECT * FROM tbl_runing_doc WHERE run_type = 'AD' LIMIT 1";
	$recordset = $objConn->Execute($sqlCommand);
	while (!$recordset->EOF) {
		$run_no = $recordset->fields["run_no"];
		$recordset->MoveNext();
	}

	// check gl description in db
    for ($index = 0; $index <= (int) $_POST["HIDnum_row"]; $index++) {

	    $sqlCommandGL = "SELECT * FROM tbl_gl WHERE gl_description = '" . $_POST["TXTdescription"][$index] . "' LIMIT 1";
	    $recordsetGL = $objConn->Execute($sqlCommandGL);

		if ($recordsetGL->RecordCount() <= 0) {
			echo "{";
			echo '"POSTING_ERROR":"ไม่พบรายการ \"' . $_POST["TXTdescription"][$index] . '\" ในระบบ กรุณาเลือกให้ถูกต้อง"';
			echo "}";
			exit();
		}

	}

	// insert item in adj document
    for ($index = 0; $index <= (int) $_POST["HIDnum_row"]; $index++) {

	    // execute the query and get empty recordset
	    $sqlCommand = "SELECT * FROM tbl_adj WHERE adj_id = -1";
	    $recordset = $objConn->Execute($sqlCommand);

	    // record data to insert
	    $record = array();

	    $record["adj_docdate"] = $_POST["TXTdoc_date"][0];

		// gl line item
	    $sqlCommandGL = "SELECT * FROM tbl_gl WHERE gl_description = '" . $_POST["TXTdescription"][$index] . "' LIMIT 1";
	    $recordsetGL = $objConn->Execute($sqlCommandGL);
	    $record["adj_account_desc"] = $recordsetGL->fields["gl_account"];

	    $record["adj_description"] = $_POST["TXTdescription"][$index];
	    $record["adj_quantity"] = $_POST["TXTquantity"][$index];
	    $record["adj_price_unit"] = $_POST["TXTprice_unit"][$index];

	    $record["adj_payer_new"] = $_POST["SELpayer"][$index];
	    //$record["adj_payer"] = $_POST["TXTpayer"][$index]; "*- not use anymore
	    $record["adj_remark"] = $_POST["TXTremark"][$index];

	    $record["adj_account_shuttlecock"] = '1201';
	    $record["adj_amount_shuttlecock"] = $_POST["TXTshuttlecock"][$index];

	    $record["adj_account_softdrink"] = '1202';
	    $record["adj_amount_softdrink"] = $_POST["TXTsoftdrink"][$index];

	    $record["adj_account_mineral"] = '1203';
	    $record["adj_amount_mineral"] = $_POST["TXTmineral"][$index];

	    $record["adj_account_water"] = '1204';
	    $record["adj_amount_water"] = $_POST["TXTwater"][$index];

	    $record["adj_docno"] = $run_no;
	    $record["adj_type"] = "ADJ1";

	    $record["created_date"] = time();
	    $record["modified_date"] = time();

		if (isset($_POST["BTTpost"])) { // post to database
			// generating insert sql
			$sqlCommand = $objConn->GetInsertSQL($recordset, $record);

			// insert the record into database
			$objConn->Execute($sqlCommand);

			// returns the last auto numbering ID inserted
			//$auto_id = $objConn->Insert_ID();
		}

		// calc. sum amount for show
		$total_amount_shuttlecock = $total_amount_shuttlecock + $_POST["TXTshuttlecock"][$index];
		$total_amount_softdrink = $total_amount_softdrink + $_POST["TXTsoftdrink"][$index];
		$total_amount_mineral = $total_amount_mineral + $_POST["TXTmineral"][$index];
		$total_amount_water = $total_amount_water + $_POST["TXTwater"][$index];

	}

	echo "{";
	echo '"TXTtotal_amount_shuttlecock":"' . $total_amount_shuttlecock . '",';
	echo '"TXTtotal_amount_softdrink":"' . $total_amount_softdrink . '",';
	echo '"TXTtotal_amount_mineral":"' . $total_amount_mineral . '",';
	echo '"TXTtotal_amount_water":"' . $total_amount_water . '",';

	if (isset($_POST["BTTpost"])) {  // update ar running no.
		// update runing no.
		$sqlCommand = "SELECT * FROM tbl_runing_doc WHERE run_type = 'AD'";
		$recordset = $objConn->Execute($sqlCommand);

		// record data to update
		$record = array();

		$record["run_no"] = $run_no + 1;

		$record["created_date"] = time();
		$record["modified_date"] = time();

		// generating update sql
		$sqlCommand = $objConn->GetUpdateSQL($recordset, $record);

		// update the record into database
		$objConn->Execute($sqlCommand);
	}

/*™*******************************************************************************************™*/

	// return json format
	$location = "./adj1_form.php";

	if (isset($_POST["BTTpost"])) {  // ar balance
		echo '"POSTING_SUCCESS":"การบันทึกรายการเสร็จสมบรูณ์ ได้เอกสารเลขที่ ' . $run_no . '",';
		echo '"POSTING_REDIRECT":"' . urlencode($location) . '"';
		echo "}";
		exit();
	} elseif (isset($_POST["BTTsimulate"])) {
		echo '"SIMULATE_SUCCESS":"ไม่พบข้อผิดพลาดในรายการ สามารถทำการบันทึกรายการได้"';
		echo "}";
		exit();
	} else {
		echo '"SIMULATE_FAIL":"พบข้อผิดพลาดในการตรวจสอบข้อมูลรายการ"';
		echo "}";
		exit();
	}

/*™*******************************************************************************************™*/
?>